﻿namespace Blaze.Editor
{
    using System;
    using UnityEditor;

    /// <summary>
    /// 为<see cref="SerializedProperty"/>提供扩展功能。
    /// </summary>
    public static class SerializedPropertyExtension
    {
        /// <summary>
        /// 读取属性到数组中。
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        public static T[] ReadArray<T>(this SerializedProperty property) where T : UnityEngine.Object
        {
            if (!property.isArray)
                throw new InvalidOperationException("not an array");

            var ret = new T[property.arraySize];
            for (var i = 0; i < ret.Length; i++)
                ret[i] = (T) property.GetArrayElementAtIndex(i).objectReferenceValue;
            return ret;
        }

        /// <summary>
        /// 将数组内的元素写入到属性中。
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        public static void WriteArray<T>(this SerializedProperty property, T[] array) where T : UnityEngine.Object
        {
            property.ClearArray();
            property.arraySize = array.Length;
            for (var i = 0; i < array.Length; i++)
                property.GetArrayElementAtIndex(i).objectReferenceValue = array[i];
        }
    }
}